<template>
<div class="content">
        <div class="chatHeader">
            <div class="back" @click="goBack">返回</div>
            <div class="title">某个人</div>
            <div class="setting">设置</div>
        </div>
	<div class="chatbox">
		<!-- <div class="usr_list">
			<span>{{roomInfo.roomMaster}}的房间</span>

			<ul>
				<li>用户在线列表</li>
				<li v-for="(item,index) in chatMember" :key="index">{{item}}</li>
			</ul>
		</div> -->
		<div class="msg_box">
			<div class="msg_play">
				<!-- 消息头部提示 -->
				<!-- <div class="notice">
					<ul>
						<li style="color:red;font-size:20px;font-weight:600">消息提示最多显示三条</li>
						<li v-for="(item,index) in tip" :key="index">
							<span>消息提示：</span>
							<span>{{item}}</span>
						</li>
					</ul>
				</div> -->
				<!-- 主体消息内容 -->
				<div class="msg_main_contain" id="msg_main_contain">
					<ul>
						<li
							class="chatRecord"
							v-for="(item,index) in chatRecord"
							:key="index"
							:class="[curUser==item.admin?'right':'left']"
						>
							<span>{{item.admin}}</span>:
							<span>{{item.msg}}</span>
						</li>
					</ul>
				</div>
			</div>
			<!-- 消息发送 -->
			<div class="msg_send">
				<textarea class="msg_input" v-model="message" @keydown.enter="enter(message)" />
				<input type="button" value="发送" @click="send(message)"  />
			</div>
		</div>
	</div>
    </div>
</template>

<script>
export default {
	name: "webChat",
	props: {
		msg: String,
	},
	data() {
		return {
			tip: [],
			chatRecord: [],
			message: "",
			chatMember: [],
			roomInfo: {},
			curUser: JSON.parse(localStorage.getItem("chatUser")).admin,
		};
	},
	methods: {
		send(message) {
			if (!window.WebSocket) {
				return;
			}
			if (this.socket && this.socket.readyState == WebSocket.OPEN) {
                var area = document.getElementById("responseText");
                //发送数据
				this.socket.send(JSON.stringify( {admin:this.curUser,msg:message} ));
				this.message = "";
				//滚动条总保持最下端
			} else {
                alert("连接没有开启.");
                this.$router.go(-1)
			}
		},

		//清除消息
		clear() {
			this.tip = [];
		},

		//监听enter
		enter(message) {
            // console.log('message: ', message);
			this.send(message);
			this.message = "";
		},

        goBack(){
            this.$router.go(-1)
        }
	},
	beforeCreate() {},
	created() {
        
        this.roomInfo = this.$route.query;
        console.log('this.$route.query: ', this.$route.query);
	},
	mounted() {
        let mainMsg = document.getElementById("msg_main_contain");
        let user = JSON.parse(localStorage.chatUser)
        console.log('user: ', user);
		var socket;
		if (!window.WebSocket) {
			window.WebSocket = window.MozWebSocket;
		}
		if (window.WebSocket) {
			let exp = new Date().getTime() + 1000 * 60 * 60;
			document.cookie = `username=${user.admin}; expires=${new Date(
				exp
			).toGMTString()}`;
			document.cookie = `token=${user.token}; expires=${new Date(
				exp
			).toGMTString()} `;
			if (!user) {
				return false;
			}
			this.socket = new WebSocket(`ws://${process.env.VUE_APP_BASE_URL}`);
			//连接建立成功回调
			this.socket.onopen = () => {
                console.log('连接开启')
				this.socket.send(JSON.stringify( {admin:this.curUser,msg:`欢迎${this.curUser}进入房间`} ));
			};

			//连接关闭回调
			this.socket.onclose = () => {
				this.tip.push("连接关闭");
			};

			//接受消息回调
			this.socket.onmessage = (event) => {
                var data = JSON.parse(event.data);
                console.log('返回data: ', data);
				switch (data.type) {
					case "join":
						console.log(this.tip);
						this.tip.push(data.msg);
						if (this.tip.length > 3) {
							this.tip.shift();
						}
						this.chatMember = data.admin;
						break;
					case "leave":
						this.tip.push(data.msg);
						if (this.tip.length > 3) {
							this.tip.shift();
						}
						var userIndex = this.chatMember.indexOf(data.admin);
						this.chatMember.splice(userIndex, 1);
						break;
					case "normal":
						// 利用异步将滚动条保持最底部
						var keep = new Promise((resolve, reject) => {
                            resolve();
                            console.log(data)
							this.chatRecord.push(data);
						});
						keep.then((res) => {
							mainMsg.scrollTop =
								mainMsg.scrollHeight - mainMsg.clientHeight;
						});
						break;
					default:
						break;
				}
			};
		} else {
			alert("你的浏览器不支持 WebSocket！");
		}
	},
	beforeDestroy() {
		//发送关闭请求
		this.socket.close();
	},
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
h3 {
	margin: 40px 0 0;
}
ul {
	list-style-type: none;
	padding: 0;
}
li {
	display: inline-block;
	margin: 0 10px;
}
a {
	color: #42b983;
}

@font-face {
	font-family: "fontello";
	src: url("../assets/font/fontello.eot?68245288");
	src: url("../assets/font/fontello.eot?68245288#iefix")
			format("embedded-opentype"),
		url("../assets/font/fontello.woff?68245288") format("woff"),
		url("../assets/font/fontello.ttf?68245288") format("truetype"),
		url("../assets/font/fontello.svg?68245288#fontello") format("svg");
	font-weight: normal;
	font-style: normal;
}
.chatHeader{
    padding: 10px 24px;
    font-size: 16px;
    display: flex;
    justify-content: space-between;
}
/*chatbox*/
.chatbox {
	background: #176994;
	overflow: hidden;
	height: calc(100vh - 41px);
	width: 100%;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	border-radius: 5px;
	background-color: rgba(255, 255, 255, 1);
	display: flex;
}
// chat play
.msg_box {
	background: #fff;
	box-sizing: border-box;
	width: 100%;
}
// user list
.usr_list {
	width: 22.5%;
}
.usr_list > ul > li {
	display: block;
	color: #fff;
	line-height: 40px;
	font-size: 24px;
}

//msg display
.msg_play {
	height: 70vh;
	box-sizing: border-box;
	border-bottom: 1px solid gray;
	overflow: hidden;
}

.msg_main_contain {
	overflow-y: scroll;
	height: 100%;
}
.chatRecord {
	display: block;
	margin: 30px 0;
	line-height: 30px;
	word-break: break-all;
}
.chatRecord.left {
	display: flex;
	flex-direction: row;
}
.chatRecord.right {
	display: flex;
	flex-direction: row-reverse;
}
.chatRecord > span:nth-of-type(1) {
	font-size: 20px;
}
.chatRecord.right > span:nth-of-type(2) {
	position: relative;
	text-align: left;
	top: 25px;
	left: -10px;
	max-width: 60%;
	background-color: #b9f6fc;
	font-size: 16px;
	color: #36efcd;
	border-radius: 25px;
	box-sizing: border-box;
	padding: 10px 20px;
}
.chatRecord.left > span:nth-of-type(2) {
	position: relative;
	text-align: left;
	top: 25px;
	left: 40px;
	max-width: 60%;
	background-color: #b9f6fc;
	font-size: 16px;
	color: #36efcd;
	border-radius: 25px;
	box-sizing: border-box;
	padding: 10px 20px;
}
.chatRecord.right > span:nth-of-type(2)::after {
	content: "";
	position: absolute;
	top: 0;
	right: -20px;
	width: 20px;
	height: 20px;
	border-width: 0 0 20px 20px;
	border-style: solid;
	border-bottom-color: #b9f6fc;
	/*自动继承父元素的border-bottom-color*/
	border-left-color: transparent;
	border-radius: 0 0 60px 0;
}
.chatRecord.left > span:nth-of-type(2)::after {
	content: "";
	position: absolute;
	top: 0;
	left: -26px;
	width: 14px;
	height: 14px;
	border-width: 0px 20px 20px 0;
	border-style: solid;
	border-bottom-color:#b9f6fc;
	border-right-color: transparent;
	border-radius: 0 0 0 60px;
}

// 右侧滚动条
.msg_main_contain::-webkit-scrollbar {
	width: 8px;
}
.msg_main_contain::-webkit-scrollbar-thumb {
	background: transparent;
	border-radius: 4px;
}
.msg_main_contain:hover::-webkit-scrollbar-thumb {
	background: #c1c1c1;
	-webkit-box-shadow: inset 3px 3px 3px #f4f4f4;
	box-shadow: inset 3px 3px 3px #f4f4f4;
}
.msg_main_contain::-webkit-scrollbar-track {
	background: transparent;
	border-radius: 4px;
}
.msg_main_contain::-webkit-scrollbar-track:hover {
	-webkit-box-shadow: inset 0 0 6px rgba(169, 163, 163, 0.3);
	box-shadow: inset 0 0 6px rgba(169, 163, 163, 0.3);
	background: #f4f4f4;
}

// 顶部提醒
.notice {
	height: 12%;
	border-bottom: 1px solid skyblue;
}
.notice > ul > li {
	display: block;
}

//msg input and send
.msg_send {
	height: 29%;
}
.msg_input {
	width: 100%;
	height: 65%;
	resize: none;
}
input[type="button"] {
	width: 50%;
	background-color: #176994;
	height: 30px;
	color: #fff;
}
</style>
